(function($) {
$(document).ready(function() {
	var validator = $("#add_form").validate({
		rules: {
			'ordersip[ip]': {
				required: true
			},
			'ordersip[name]': {
				required: true,
				check_hostname: true
			},
			'ordersip[mac]': {
				required: true,
				check_mac: true
			}
		},
		messages: {
			'ordersip[ip]': {
				required: "Введите ip"
			},
			'ordersip[name]': {
				required: "Введите имя"
			},
			'ordersip[mac]': {
				required: "Введите mac"
			}
		},

		errorPlacement: function(error, element) {
			if ( element.is(":radio") )
				error.appendTo( element.parent().next().next() );
			else if ( element.is(":checkbox") )
				error.appendTo ( element.next() );
			else
				error.appendTo( element.parent().next() );
		},

		submitHandler: function() {
			
			form.submit();
		},
                
		success: function(label) {
			// set &nbsp; as text for IE
			label.html("&nbsp;").addClass("checked");
		},
		onfocusout: false,
		onkeyup: false,
		onclick: false
	});
	
	$.validator.addMethod("check_hostname", function(value, element) 
	{
                var hostname = $('#hide_hostname').html();
                var new_hostname = $('#ordersip_name').val();
                if (hostname == new_hostname)
                    return true;
		var check_hostname = $.ajax({ type: "GET", url: "./../ip_check_hostname/"+value, async: false }).responseText;
		if (check_hostname != "true")
		{
			$.validator.messages.check_hostname = check_hostname;
			return false;
		}
		else
			return true;
	}
	);
	
	$.validator.addMethod("check_mac", function(value, element)
	{
                var mac = $('#hide_mac').html();
                var new_mac = $('#ordersip_mac').val();
                if (mac == new_mac)
                    return true;
		var check_mac = $.ajax({ type: "GET", url: "./../ip_check_mac/"+value, async: false }).responseText;
		if (check_mac != "true")
		{
			$.validator.messages.check_mac = check_mac;
			return false;
		}
		else
			return true;
	}
	);
});

})(jQuery);
